//
//  M_MineSettingViewController.m
//  Model
//
//  Created by apple on 2018/7/10.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "M_MineSettingViewController.h"
#import "M_MineSettingTableViewCell.h"
#import "M_MineAboutUsViewController.h"//关于我们
#import "AboutUSaViewController.h"//免责声明
#import "M_MineHelpZXViewController.h"
#import "ChoiceLoginViewController.h"
@interface M_MineSettingViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) UILabel *cacheLabel;
@end

@implementation M_MineSettingViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    [self creationView];
    [self regeditCell];
    self.view.backgroundColor = getColor(@"f7f7f7");
    // Do any additional setup after loading the view.
}
- (void)creationView{
    self.tableView = [[UITableView alloc] init];
    self.tableView.frame = CGRectMake(0, 10, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-30);
    
    self.tableView.tableFooterView = [[UITableView alloc] initWithFrame:CGRectZero];
    
    self.tableView.backgroundColor = getColor(@"f7f7f7");
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    UIButton *tuiChuBtn = [[UIButton alloc] init];
    [self.view addSubview:tuiChuBtn];
    [tuiChuBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.bottom.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.offset(50);
        
    }];
    tuiChuBtn.backgroundColor = getColor(@"ff40c6");
    tuiChuBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    [tuiChuBtn setTitleColor:[UIColor colorWithRed:255/255.0f green:255/255.0f blue:255/255.0f alpha:1] forState:UIControlStateNormal];
    [tuiChuBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [tuiChuBtn addTarget:self action:@selector(tuiChuClikc) forControlEvents:UIControlEventTouchUpInside];
    
}
#pragma mark ---------- 退出登录
- (void)tuiChuClikc{
    ChoiceLoginViewController *vc = [[ChoiceLoginViewController alloc] init];
    //user_id
    [self presentViewController:vc animated:YES completion:^{
        
        [PublicFunction removeConfigWithKey:@"user_id"];
        NSLog(@"%@", [PublicFunction getConfigWithKey:@"user_id"]);
//        NSString *encryStr = [returnData[@"Data"] aci_encryptWithAES];
        
        [PublicFunction removeConfigWithKey:@"token"];
        NSLog(@"%@", [PublicFunction getConfigWithKey:@"token"]);
        
    }];
    
}
- (void)regeditCell{
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"M_MineSettingTableViewCell" bundle:nil] forCellReuseIdentifier:@"M_MineSettingTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"M_MineTwoTableViewCell" bundle:nil] forCellReuseIdentifier:@"M_MineTwoTableViewCell"];
    
    
}
#pragma mark - ---------- Section的数量 ----------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark - ---------- 每个Section的高度 ----------
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 0;
}

#pragma mark - ---------- Cell的数量 ----------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
    
}

#pragma mark - ---------- 每个Cell的高度 ----------
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
   
}
#pragma mark - ---------- 每个Cell的内容 ----------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    M_MineSettingTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"M_MineSettingTableViewCell" forIndexPath:indexPath];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    NSArray *arr = @[@"清除缓存",@"检查更新", @"关于我们", @"免责声明", @"帮助中心"];
    cell.titLab.text = arr[indexPath.row];
        
    if (indexPath.row == 0) {
        
        if (self.cacheLabel) {
            [self.cacheLabel removeFromSuperview];
            
        }
        
        self.cacheLabel = [[UILabel alloc] init];
        self.cacheLabel.textAlignment = NSTextAlignmentRight;
        self.cacheLabel.font = [UIFont systemFontOfSize:13];
        self.cacheLabel.text = [NSString stringWithFormat : @"%.2fM" , [self filePath]];
        [cell addSubview:self.cacheLabel];
        [self.cacheLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell).with.offset(10);
            make.right.equalTo(cell).with.offset(-40);
            make.bottom.equalTo(cell).with.offset(-10);
            make.width.offset(100);
        }];
  
    }

    return cell;
   

}

#pragma mark - ---------- 每个Cell的点击事件 ----------
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否清除缓存" preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
            [self clearFile];
            
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
        [alert addAction:action];
        [alert addAction:cancel];
        [self showDetailViewController:alert sender:nil];
        //清除缓存
    }else if (indexPath.row == 2){
        
        M_MineAboutUsViewController *vc = [[M_MineAboutUsViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
        
    }else if (indexPath.row == 4){
        
        M_MineHelpZXViewController *vc = [[M_MineHelpZXViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    else if (indexPath.row == 1){
        
        
        [self gengXin];
    }else if (indexPath.row == 3){
        
        AboutUSaViewController *vc = [[AboutUSaViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
}
//首先计算单个文件的大小

- (long long)fileSizeAtPath:(NSString *)filePath{
    
    NSFileManager * manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error : nil] fileSize];
        
    }
    
    return 0 ;
    
}

//遍历文件夹获得文件夹大小，返回多少M

- (float)folderSizeAtPath:(NSString *)folderPath{
    
    NSFileManager * manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath]) return 0 ;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator];
    
    NSString * fileName;
    
    long long folderSize = 0 ;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
        
    }
    
    return folderSize/( 1024.0 * 1024.0 );
    
}

// 显示缓存大小

- (float)filePath

{
    
    NSString * cachPath = [NSSearchPathForDirectoriesInDomains( NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    
    return [self folderSizeAtPath:cachPath];
    
}

// 清理缓存

- (void)clearFile

{
    
    NSString * cachPath = [NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    
    NSArray * files = [[NSFileManager defaultManager] subpathsAtPath :cachPath];
    
    NSLog (@"cachpath = %@" , cachPath);
    
    for (NSString *p in files) {
        
        NSError *error = nil ;
        
        NSString *path = [cachPath stringByAppendingPathComponent:p];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath :path]){
            
            [[NSFileManager defaultManager] removeItemAtPath :path error :&error];
            
        }
        
    }
    
    [self performSelectorOnMainThread:@selector(clearCachSuccess) withObject:nil waitUntilDone:YES];
    
}

- (void)clearCachSuccess

{
    
    NSLog(@"清理成功");
    
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message: @"缓存清理完毕" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    
    [alertView show];
    self.cacheLabel.text = nil;
    
    [self.tableView reloadData];//清理完之后重新导入数据
    
}
#pragma mark --------- 检查更新
- (void)gengXin{
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];

    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary]; 
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    [productParams setValue:app_Version forKey:@"v"];
    [[MNetworkHandler sharedInstance]conURL:actionupgrade networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
        
        if ([[returnData objectForKey:@"Status"]intValue]==200) {
            NSString *textURL = returnData[@"Data"];
            NSURL *cleanURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@", textURL]];
            [[UIApplication sharedApplication] openURL:cleanURL];
 
            
        }
        
        else {
            
            [PublicFunction showAlert:nil message:[returnData objectForKey:@"Msg"] duration:5.0f];
            //            [hud removeFromSuperview];
            
        }
        
    } failureBlock:^(NSError *error) {
        
        NSLog(@"%@",error);
        
        [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
        //        [hud removeFromSuperview];
    }];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
